<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="queryParams.startTime"
          type="date"
          placeholder="选择开始时间"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="queryParams.endTime"
          type="date"
          placeholder="选择结束时间"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="商品ID" prop="goodId">
        <el-input
          v-model="queryParams.goodId"
          placeholder="请输入商品ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20">
      <!-- 评论统计数据 -->
      <el-col :span="24">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>评论统计数据</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="4">
              <div class="statistic-item">
                <div class="statistic-value">{{ commentStats.totalComments || 0 }}</div>
                <div class="statistic-label">总评论数</div>
              </div>
            </el-col>
            <el-col :span="4">
              <div class="statistic-item">
                <div class="statistic-value">{{ (commentStats.avgRating || 0).toFixed(1) }}</div>
                <div class="statistic-label">平均评分</div>
              </div>
            </el-col>
            <el-col :span="4">
              <div class="statistic-item">
                <div class="statistic-value">{{ commentStats.positiveComments || 0 }}</div>
                <div class="statistic-label">好评数</div>
              </div>
            </el-col>
            <el-col :span="4">
              <div class="statistic-item">
                <div class="statistic-value">{{ commentStats.negativeComments || 0 }}</div>
                <div class="statistic-label">差评数</div>
              </div>
            </el-col>
            <el-col :span="4">
              <div class="statistic-item">
                <div class="statistic-value">{{ commentStats.todayComments || 0 }}</div>
                <div class="statistic-label">今日评论</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 评论评分分布 -->
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>评分分布</span>
          </div>
          <div ref="ratingChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      
      <!-- 售后统计数据 -->
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>售后统计</span>
          </div>
          <el-row :gutter="10">
            <el-col :span="12">
              <div class="statistic-item">
                <div class="statistic-value">{{ afterServiceStats.totalAfterService || 0 }}</div>
                <div class="statistic-label">总售后数</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="statistic-item">
                <div class="statistic-value">{{ (afterServiceStats.avgProcessTime || 0).toFixed(1) }}h</div>
                <div class="statistic-label">平均处理时长</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="statistic-item">
                <div class="statistic-value">{{ afterServiceStats.resolvedCount || 0 }}</div>
                <div class="statistic-label">已解决</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="statistic-item">
                <div class="statistic-value">{{ afterServiceStats.pendingCount || 0 }}</div>
                <div class="statistic-label">处理中</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 售后类型分布 -->
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>售后类型分布</span>
          </div>
          <div ref="afterServiceChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      
      <!-- 评论关键词 -->
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>评论关键词</span>
          </div>
          <div ref="keywordsChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import {
  getMockCommentStatistics,
  getMockAfterServiceStatistics,
  getMockCommentRatingDistribution,
  getMockAfterServiceCategory,
  getMockCommentKeywords
} from '@/api/statistics/commentAfterService'

export default {
  name: "CommentAfterService",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        startTime: null,
        endTime: null,
        goodId: null
      },
      // 评论统计数据
      commentStats: {},
      // 售后统计数据
      afterServiceStats: {},
      // 图表实例
      ratingChart: null,
      afterServiceChart: null,
      keywordsChart: null
    };
  },
  created() {
    this.getCommentStatistics();
    this.getAfterServiceStatistics();
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts();
    });
  },
  beforeDestroy() {
    if (this.ratingChart) {
      this.ratingChart.dispose();
    }
    if (this.afterServiceChart) {
      this.afterServiceChart.dispose();
    }
    if (this.keywordsChart) {
      this.keywordsChart.dispose();
    }
  },
  methods: {
    /** 搜索按钮操作 */
    handleQuery() {
      this.getCommentStatistics();
      this.getAfterServiceStatistics();
      this.getCommentRatingDistribution();
      this.getAfterServiceCategory();
      this.getCommentKeywords();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 获取评论统计数据 */
    getCommentStatistics() {
      getMockCommentStatistics().then(response => {
        this.commentStats = response.data || {};
      }).catch(error => {
        console.error('获取评论统计数据失败:', error);
        this.$message.error('获取评论统计数据失败');
      });
    },
    /** 获取售后统计数据 */
    getAfterServiceStatistics() {
      getMockAfterServiceStatistics().then(response => {
        this.afterServiceStats = response.data || {};
      }).catch(error => {
        console.error('获取售后统计数据失败:', error);
        this.$message.error('获取售后统计数据失败');
      });
    },
    /** 获取评论评分分布 */
    getCommentRatingDistribution() {
      getMockCommentRatingDistribution().then(response => {
        this.updateRatingChart(response.data || []);
      }).catch(error => {
        console.error('获取评论评分分布失败:', error);
      });
    },
    /** 获取售后类型分布 */
    getAfterServiceCategory() {
      getMockAfterServiceCategory().then(response => {
        this.updateAfterServiceChart(response.data || []);
      }).catch(error => {
        console.error('获取售后类型分布失败:', error);
      });
    },
    /** 获取评论关键词 */
    getCommentKeywords() {
      getMockCommentKeywords().then(response => {
        this.updateKeywordsChart(response.data || []);
      }).catch(error => {
        console.error('获取评论关键词失败:', error);
      });
    },
    /** 初始化图表 */
    initCharts() {
      this.ratingChart = echarts.init(this.$refs.ratingChart);
      this.afterServiceChart = echarts.init(this.$refs.afterServiceChart);
      this.keywordsChart = echarts.init(this.$refs.keywordsChart);
      
      // 获取图表数据
      this.getCommentRatingDistribution();
      this.getAfterServiceCategory();
      this.getCommentKeywords();
    },
    /** 更新评分分布图表 */
    updateRatingChart(data) {
      if (!this.ratingChart) return;
      
      // 处理数据格式，支持数组和对象两种格式
      let chartData = [];
      if (Array.isArray(data)) {
        chartData = data.map(item => ({
          value: item.count || 0,
          name: `${item.rating || 0}星`
        }));
      } else {
        chartData = [
          { value: data.rating5 || 0, name: '5星' },
          { value: data.rating4 || 0, name: '4星' },
          { value: data.rating3 || 0, name: '3星' },
          { value: data.rating2 || 0, name: '2星' },
          { value: data.rating1 || 0, name: '1星' }
        ];
      }
      
      const option = {
        title: {
          text: '评分分布',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: chartData.map(item => item.name)
        },
        series: [
          {
            name: '评分分布',
            type: 'pie',
            radius: '50%',
            center: ['50%', '60%'],
            data: chartData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            itemStyle: {
              color: function(params) {
                const colors = ['#67C23A', '#85ce61', '#FFBA00', '#F56C6C', '#909399'];
                return colors[params.dataIndex] || '#409EFF';
              }
            }
          }
        ]
      };
      
      this.ratingChart.setOption(option);
    },
    /** 更新售后类型分布图表 */
    updateAfterServiceChart(data) {
      if (!this.afterServiceChart) return;
      
      const option = {
        title: {
          text: '售后类型分布',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: data.map(item => item.category || '未知')
        },
        series: [
          {
            name: '售后类型',
            type: 'pie',
            radius: '50%',
            center: ['50%', '60%'],
            data: data.map(item => ({
              value: item.count || 0,
              name: item.category || '未知'
            })),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            itemStyle: {
              color: function(params) {
                const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399'];
                return colors[params.dataIndex] || '#73c0de';
              }
            }
          }
        ]
      };
      
      this.afterServiceChart.setOption(option);
    },
    /** 更新关键词图表 */
    updateKeywordsChart(data) {
      if (!this.keywordsChart) return;
      
      const option = {
        title: {
          text: '评论关键词',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            const data = params[0];
            return `关键词: ${data.name}<br/>出现次数: ${data.value}`;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.keyword || ''),
          axisLabel: {
            rotate: 45,
            fontSize: 12
          },
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: {
          type: 'value',
          name: '出现次数',
          nameTextStyle: {
            fontSize: 12
          }
        },
        series: [
          {
            name: '出现次数',
            type: 'bar',
            data: data.map(item => item.count || 0),
            itemStyle: {
              color: function(params) {
                const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399'];
                return colors[params.dataIndex % colors.length];
              },
              borderRadius: [4, 4, 0, 0]
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.3)'
              }
            }
          }
        ]
      };
      
      this.keywordsChart.setOption(option);
    }
  }
};
</script>

<style scoped>
.statistic-item {
  text-align: center;
  padding: 20px 0;
}

.statistic-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
}

.statistic-label {
  font-size: 14px;
  color: #666;
}

.box-card {
  margin-bottom: 20px;
}
</style>